package com.lkk.cg.service.impl;

import com.lkk.cg.base.DaoSupportImpl;
import com.lkk.cg.domain.Article;
import com.lkk.cg.domain.User;
import com.lkk.cg.service.ArticleService;
import com.lkk.cg.util.DateUtils;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

import static com.lkk.cg.util.NumberUtils.convertToLong;

/**
 * Created by lkk on 2014/12/14.
 */
@Transactional
public class ArticleServiceImpl extends DaoSupportImpl<Article> implements ArticleService {

    public List<Article> getByAuthor(User author) {

        Session session = getSession();
        Query query = session.createQuery("from " + clazz.getSimpleName() + " as a where a.author=:author")
                .setParameter("author", author);
        return query.list();
    }

    public Long countTodayPost() {

        Session session = getSession();
        DateUtils dateUtils = new DateUtils();
        Query query = session.createQuery("select count(a) from Article a where a.createTime >= :start and a.createTime <= :last")
                .setParameter("start", dateUtils.firstSecondOfDay())
                .setParameter("last", dateUtils.lastSecondOfDay());
        return convertToLong(query.uniqueResult());
    }

    public Long countTodayDownload() {
        Session session = getSession();
        DateUtils dateUtils = new DateUtils();
        Query query = session.createQuery("select sum(a.downloadCount) from Article a where a.createTime >= :start and a.createTime <= :last")
                .setParameter("start", dateUtils.firstSecondOfDay())
                .setParameter("last", dateUtils.lastSecondOfDay());
        return convertToLong(query.uniqueResult());

    }

    public Long countTotalPost() {
        Session session = getSession();
        Query query = session.createQuery("select count(*) from Article");
        return convertToLong(query.uniqueResult());
    }

    public Long countTotalDownload() {
        Session session = getSession();
        Query query = session.createQuery("select sum(a.downloadCount) from Article a");
        return convertToLong(query.uniqueResult());
    }

    public List<Article> getMostDownload() {
        Session session = getSession();
        Query query = session.createQuery("from " + clazz.getSimpleName() + " as a order by a.downloadCount desc")
                .setMaxResults(5)
                .setFirstResult(0);
        return query.list();
    }

    public List<Article> getLastedAdded() {
        Session session = getSession();
        Query query = session.createQuery("from " + clazz.getSimpleName() + " as a order by a.createTime desc")
                .setMaxResults(5)
                .setFirstResult(0);
        return query.list();
    }

}
